<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use app\common\service\ProductService;
use fast\Tree;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{

    /**
     * Category模型对象
     * @var \app\admin\model\product\Category
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\product\Category;

    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
//    public function index()
//    {
//        if (!$this->request->isAjax()) {
//            return $this->view->fetch();
//        }
//
//        $list = $this->model->with('children.children')->where('pid', 0)->select();               // 查询全部
//        $this->success('', null, $list);
//    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
//            ->with('children.children')
            ->where($where)
            ->select();
//        $list = (new ProductService())->productCategoryTree($where);

        $objList = []; $ids=[];
        foreach ($list as $k => $v) {
            $childrenList = Tree::instance()->init($list, 'pid')->getChildren($v['id'], true);
            $obj = Tree::instance()->init($childrenList, 'pid')->getTreeArray($v['pid']);

//                $objList[]=$obj;
            if(!in_array($obj[0]->id,$ids)){
                $rr=  Tree::instance()->getTreeListNew($obj);

                if($rr){
                    foreach ($rr as $ke=>$v1){
                        $objList[]=$v1;
                        $ids[]= $v1['id'];
                    }

                }
            }
//            array_push($objList,$rr);
        }
        if (!empty($objList)) {

            $objList = collection($objList)->toArray();
            foreach ($objList as $k=>$v){
                $objList[$k]['name']= str_replace('&nbsp;','',$v['name']);
            }

        }
        $result = ['rows' => $objList];
        return json($result);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function categoryTreeLists()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $params = $this->request->param();
        $where = [];
        if (isset($params['name']) && !empty($params['name'])) {
            $where = 'name LIKE "%' . $params['name'] . '%"';

        }
        if (isset($params['searchKey']) && $params['searchKey'] == 'id') {

            $where = 'id = ' . $params['keyValue'] ?: 0;
            if($params['keyValue']==0){
                $returnData = [
                    'rows' => ['id' => 0, "pid" => 0, 'name' => '顶级分类', 'haschild' => 0],
                    'total' => 1
                ];
                return json($returnData);
            }
        }
//        var_dump($where);
        $data = (new ProductService())->productCategoryTree($where);
        return json($data);
    }

    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $categories = (new \addons\shopro\library\Tree(function () {
            // 组装搜索条件，排序等
            return $this->model->field("id,name,pid,type")
                ->order('type', 'desc');
        }))->getTree(0,'pid');

        $this->success('获取成功', null, $categories);
    }


}
